package com.up.vms.interfaces.rest.controller;

import com.alibaba.fastjson.JSON;
import com.baidu.ueditor.ActionEnter;
import com.up.vms.infrastructure.util.CommonUtils;
import com.up.vms.interfaces.rest.utils.UploadFile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import com.up.vms.interfaces.rest.component.QnOssManager;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Controller
public class ServerController {

    @Autowired
    private QnOssManager qnOssManager;

    @RequestMapping(value = "/config", method = RequestMethod.GET)
    public void config(HttpServletRequest request, HttpServletResponse response,
                       @RequestParam(value = "callback", required = false) String callback) {

        if (CommonUtils.isNotNull(callback)) {
            response.setContentType("text/javascript");
        } else {
            response.setContentType("application/json");
        }

        String rootPath = ClassUtils.getDefaultClassLoader().getResource("").getPath() + "";
        log.warn("rootpath==" + rootPath);

        try {
            response.setCharacterEncoding("UTF-8");
            String exec = new ActionEnter(request, rootPath).exec();
            System.out.println(exec);
            PrintWriter writer = response.getWriter();
            writer.write(new ActionEnter(request, rootPath).exec());
            writer.flush();
            writer.close();
        } catch (IOException e) {
            log.error("出现异常", e);
        }

    }


    @RequestMapping(value = "/config", method = RequestMethod.POST)
    public void configUpload(HttpServletRequest request,
                             @RequestParam(value = "action") String param,
                             MultipartFile upfile, HttpServletResponse response) {

        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        try {
            Map<String, Object> map = new HashMap<>();
            if (upfile != null) {
                map = upload(param, upfile, request);
            } else {
                map.put("state", "文件为空");
            }
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(map));
            writer.flush();
            writer.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
//    /**
//     * 加载配置文件，这个方法只是在加载时调用，上传文件接口在表单页面设置为我们自定义的uploadfile方法
//     */
//    @RequestMapping("/config")
//    public void config(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, JSONException {
//        response.setContentType("application/json");
//        String rootPath = request.getSession().getServletContext().getRealPath("/");
//        try {
//            response.setCharacterEncoding("UTF-8");
//            ActionEnter actionEnter = new ActionEnter(request, rootPath);
//            String exec = actionEnter.exec();
//            PrintWriter writer = response.getWriter();
//            writer.write(exec);
//            writer.flush();
//            writer.close();
//        } catch(Exception e){
//            log.error("出现异常", e);
//        }
//    }

    @RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> uploadImage(HttpServletRequest request, @RequestParam("upfile") MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        //封装的图片上传方法
        String path = request.getSession().getServletContext().getRealPath("/testImage");
        map.put("url", UploadFile.uploadSaveImage(file, path));//上传的图片路径
        map.put("state", "SUCCESS");
        map.put("title", file.getOriginalFilename());
        map.put("original", file.getOriginalFilename());
        return map;
    }

    @RequestMapping(value = "/uploadVideo", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> uploadVideo(HttpServletRequest request, @RequestParam("upfile") MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        String path = request.getSession().getServletContext().getRealPath("/");
        //获取保存视频路径和保存视频第一帧图片路径
        Map<String, Object> videoImage = UploadFile.uploadSaveVideo(file, path);
        map.put("url", videoImage.get("videoPath"));
        map.put("imageUrl", videoImage.get("videoImage"));
        map.put("state", "SUCCESS");
        map.put("title", file.getOriginalFilename());
        map.put("original", file.getOriginalFilename());
        return map;
    }


    /**
     * 自定义文件上传接口，我这里直接调用七牛云上传
     *
     * @param upfile upfile参数保证与config.json中imageFieldName设置一致
     * @return 返回数据格式，是ueditor规定的格式
     * @throws Exception
     */
    @RequestMapping(value = "/uploadfile", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> upload(@RequestParam("action") String param, MultipartFile upfile, HttpServletRequest request)
            throws Exception {
        Map<String, Object> rs = new HashMap<String, Object>();
        String originalFileName = "";
        try {
            if (!upfile.isEmpty()) {
                originalFileName = upfile.getOriginalFilename();
                String ct = upfile.getContentType();
                String fileTypeStr = "";
                if (ct.indexOf("/") > 0) {
                    fileTypeStr = ct.substring(ct.indexOf("/") + 1);
                }

                int fileType = qnOssManager.getFileType(upfile.getOriginalFilename());

                if (param.equals("uploadvideo")) {
                    fileType = 1;
                }

                Map<String, Object> map = qnOssManager.saveFileToQiniu(upfile.getInputStream(), fileType, originalFileName, fileTypeStr, null);//调用七牛云上传的方法，这里大家改成自己上传的方法
                System.out.println(map.get("fileUrl"));
                rs.put("state", "SUCCESS");// UEDITOR的规则:不为SUCCESS则显示state的内容
                rs.put("url", map.get("fileUrl")); // 能访问到你现在图片的路径
                rs.put("title", originalFileName);
                rs.put("original", originalFileName);
            }
        } catch (Exception e) {
            e.printStackTrace();
            rs.put("state", e.getMessage());
            rs.put("url", "");
            rs.put("title", "");
            rs.put("original", "");
        }
        return rs;
    }


//
}
